package org.amj.wn;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Servlet Filter implementation class AdminFilter
 */
public class AdminFilter implements Filter {

	private static List<String> allowedUsers = new ArrayList<String>();
	private FilterConfig fConfig;

	
	static {
		allowedUsers.add("farazpu@gmail.com");
		allowedUsers.add("waqfenou.canada@hotmail.ca");
		allowedUsers.add("waqfenou.ec@gmail.com");
		
	}
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
	    UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();
	    
	    if (user == null) {
	    	fConfig.getServletContext().getRequestDispatcher("/admin/adminlogin.jsp").forward(request, response);
	    } else if (!isValid(user)) {
		    fConfig.getServletContext().getRequestDispatcher("/admin/signout.jsp").forward(request, response);
	    } else {
			chain.doFilter(request, response);
	    }
	}

	
	
	private boolean isValid(User user) {
		if(user == null)
			return false;
		
		return allowedUsers.contains(user.getEmail().toLowerCase());
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		this.fConfig = fConfig;
		
	}

}
